package gui.Login;


import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

import javax.swing.*;

import javax.swing.border.*;

import system.FieldValidator;
import system.SystemMode;
import system.SystemTypes;
import system.VcpClient;
import system.VCP;
import control.LoginController;
import control.MessageController;
import vcpClasses.Notification;
import vcpClasses.User;
/**
 * this class use  for log in Screen
 * @author G8
 *
 */
public class UserGUI extends JPanel implements ActionListener, ItemListener
{
	private JTextField Usertxt;
	private JPasswordField passwordField;
	private JTextField textFieldIP;
	private JTextField textFieldPort;
	private JLabel UserNameLbl;
	private JLabel PassLbl;
	private JButton SubButt;
	private JLabel lblIpAddress;
	private JLabel lblPortNumber;
	private JCheckBox consettingCB=null;
	private User LogUser;
	private LoginController loginC;
	private MessageController messageController;
	private SystemTypes loginCheckResult;
	private static String cnfmsg = "Login Successfully!";
	private static final String errLgn = "Login failed, check the ID or the password and try again";
	private JLabel lblDateTime;
	/**
	 *log in Screen  Constructor 
	 */
	public UserGUI ()
	{
		super();
		loginC = new LoginController();
		initialize();
	}
	/**
	 * This method contains the view of the Panel
	 */
	private void  initialize()
	{
		setBorder(new TitledBorder(null, "Login Screen", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		setBackground(SystemColor.menu);
		setBounds(VCP.guiX,VCP.guiY,500,400);
		setLayout(null);

		add(getUnameLable());
		add(getUserText());
		add(getPassLabel());
		add(getPassText());
		add(getPortLbl());
		add(getPortxt());
		add(getIPLbl());
		add(getIPText());
		add(getChBox());
		add(getSubButt());
		
		JLabel lblWelcomeToVcp = new JLabel("Welcome to VCP System by Group 8 !");
		lblWelcomeToVcp.setBounds(52, 29, 366, 14);
		add(lblWelcomeToVcp);
		
		JLabel lblPleaseInsertThe = new JLabel("Please insert the following details in order to enter the system...");
		lblPleaseInsertThe.setBounds(52, 54, 366, 14);
		add(lblPleaseInsertThe);
		
		lblDateTime = new JLabel("Date and Time");
		lblDateTime.setBounds(201, 332, 97, 14);
		lblDateTime.setText(VCP.getDateTime());
		add(lblDateTime);
		
	}
	/**
	 * This method listens to the buttons on the panel
	 * @param e is the buttons the user Click
	 */
	public void itemStateChanged(ItemEvent e)
	{
		if (e.getItemSelectable() == consettingCB)
		{
			if (consettingCB.isSelected())
			{
				textFieldIP.setEditable(false);
				textFieldIP.setEnabled(false);
				textFieldPort.setEditable(false);
				textFieldPort.setEnabled(false);
			}
			if (!consettingCB.isSelected())
			{
				textFieldIP.setEditable(true);
				textFieldIP.setEnabled(true);
				textFieldPort.setEditable(true);
				textFieldPort.setEnabled(true);
			}
		}
	}


/**
 * this method Use for JCheckBox default connection settings
 * @return the button consettingCB 
 */
	private JCheckBox getChBox() 
	{
		consettingCB = new JCheckBox("Use default connection settings");
		consettingCB.setBackground(SystemColor.menu);
		consettingCB.setBounds(130, 230, 223, 23);
		consettingCB.setSelected(true);
		consettingCB.addItemListener(this);
		return consettingCB;
	}
	
	/**
	 * this method Use for JTextField "localhost"
	 * @return the b text Field IP 
	 */
	private JTextField getIPText() 
	{
		textFieldIP = new JTextField();
		textFieldIP.setColumns(10);
		textFieldIP.setBounds(169, 194, 249, 25);
		textFieldIP.setEnabled(false);
		textFieldIP.setEditable(false);
		textFieldIP.setText("localhost");
		return textFieldIP;
	}
	/**
	 * this method Use for JLabel "Server IP:"
	 * @return the lbl Ip Address 
	 */
	private JLabel getIPLbl() {
		lblIpAddress = new JLabel("Server IP:");
		lblIpAddress.setHorizontalAlignment(SwingConstants.LEFT);
		lblIpAddress.setBounds(62, 188, 97, 36);
		return lblIpAddress;
	}
	/**
	 * this method Use for JTextField "5555"
	 * @return the text Field Port 
	 */
	private JTextField getPortxt() {
		textFieldPort = new JTextField();
		textFieldPort.setColumns(10);
		textFieldPort.setBounds(169, 158, 249, 25);
		textFieldPort.setEnabled(false);
		textFieldPort.setEditable(false);
		textFieldPort.setText("5555");
		return textFieldPort;
	}
	/**
	 * this method Use for JLabel "Port Number:"
	 * @return the lbl Port Number
	 */
	private JLabel getPortLbl() {
		lblPortNumber = new JLabel("Port Number:");
		lblPortNumber.setHorizontalAlignment(SwingConstants.LEFT);
		lblPortNumber.setBounds(62, 152, 97, 36);
		return lblPortNumber;
	}
	/**
	 * this method Use for JLabel "Username:"
	 * @return the lbl User Name
	 */
	private JLabel getUnameLable() {
		UserNameLbl = new JLabel("Username:");
		UserNameLbl.setHorizontalAlignment(SwingConstants.LEFT);
		UserNameLbl.setBounds(62, 86, 97, 29);
		return UserNameLbl;
	}

	/**
	 * this method Use for JLabel "Password:"
	 * @return the lbl Password
	 */
	private JLabel getPassLabel() {
		PassLbl = new JLabel("Password:");
		PassLbl.setHorizontalAlignment(SwingConstants.LEFT);
		PassLbl.setBounds(62, 116, 97, 36);

		return PassLbl;
	}

	/**
	 * this method Use for JTextField Password
	 * @return the password Field
	 */
	private JTextField getPassText() {
		passwordField = new JPasswordField();
		passwordField.setHorizontalAlignment(SwingConstants.LEFT);
		passwordField.setBounds(169, 122, 249, 25);
		return passwordField;
	}
	/**
	 * this method Use for JTextField UserName
	 * @return the Usertxt
	 */
	private JTextField getUserText() {
		Usertxt = new JTextField();
		Usertxt.setBounds(169, 86, 249, 25);
		Usertxt.setColumns(10);
		return Usertxt;
	}
	/**
	 * this method Use for JButton Login
	 * @return the Login Button
	 */
	private JButton getSubButt() {
		SubButt = new JButton("Login");
		SubButt.setSize(126, 36);
		SubButt.setLocation(183, 273);
		SubButt.addActionListener(this);
		return SubButt;
	}
	/**
	 * this method clear all Fields
	 *
	 */
	private void clearFields()
	{
		Usertxt.setText(null);
		passwordField.setText(null);
		textFieldPort.setText(null);
		textFieldIP.setText(null);
	}
			
	/**
	 * This method listens to the buttons on the panel
	 * @param e is the buttons the user Click
	 */
		@Override
		public void actionPerformed(ActionEvent Ae) {
			if (Ae.getSource()==SubButt)
			{
				if (FieldValidator.checkIP(textFieldIP.getText()) && FieldValidator.checkPort(textFieldPort.getText()))
				{
					User newUser = new User(Usertxt.getText(),passwordField.getText());
					// Call login controller method verifyLoginDetails to check the user login details.
					loginCheckResult = loginC.verifyLoginDetails(textFieldIP.getText(), Integer.parseInt(textFieldPort.getText()), newUser);
					newUser = (User) loginCheckResult.getObj();
					if (loginCheckResult.getSysMode().equals(SystemMode.EMPTY_RES)) // User doesn't exist.
					{
					    JOptionPane.showMessageDialog(null, "User "+Usertxt.getText()+" doesn't exist !", "Error",
					                                    JOptionPane.ERROR_MESSAGE);
					}
					else if (loginCheckResult.getSysMode().equals(SystemMode.FAIL)) // User exists, incorrect password.
					{
						JOptionPane.showMessageDialog(null, "Incorrect password, please try again !", "Error",
		                        JOptionPane.ERROR_MESSAGE);
					}
					else if (loginCheckResult.getSysMode()==SystemMode.ALREADY_IN) // Details are correct but this user is already logged in
					{
						JOptionPane.showMessageDialog(null, "User "+Usertxt.getText()+" is already logged in !", "Error",
		                            JOptionPane.ERROR_MESSAGE);
					}
					else
					{
						
						JOptionPane.showMessageDialog(null, "Welcome, "+VCP.currentUser.getUserFirstName()+" !", "Welcome",
	                            JOptionPane.INFORMATION_MESSAGE);
						VCP.setGUI(VCP.currentUser.getPrivilege(),this);
						
						VCP.messageController = new MessageController();
						SystemTypes dummy = new SystemTypes(VCP.currentUser,null);
						VCP.currentUser.setUnreadNotif((Vector<Notification>)VCP.messageController.TimedGetMessages(dummy));
						/*int numOfMessages;
						try{
							numOfMessages = VCP.currentUser.getUnreadNotif().size();
						}
						catch(Exception e){
							numOfMessages=0;
						}
						if (numOfMessages>0){
						JOptionPane.showMessageDialog(null, "You have "+ numOfMessages+" new message(s).", "Welcome",
				                JOptionPane.INFORMATION_MESSAGE);
						}*/
					}
				}
				else
					JOptionPane.showMessageDialog(null,"Invalid field(s) detected !", "Error",JOptionPane.ERROR_MESSAGE);
			}
		}
}
